package logger.sd.examples.server;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import logger.sd.server.LoggingServer;
import logger.sd.server.ServerManager;
import logger.sd.server.ServerConfiguration;

public class TokenRingServer implements Observer {

	private static ServerManager serverManager;
	private ServerConfiguration config;
	
	/**
	 * Construtor
	 */
	public TokenRingServer(String[] args) {
		config = new ServerConfiguration();
		this.parse(this.config, args);
		
		serverManager = new ServerManager(config);
		serverManager.createLogServer();
		serverManager.getServer().addListener(this);
	}
	
	/**
	 * Funcao que le os argumentos da linha de comando.
	 * @param args
	 */
	private void parse(ServerConfiguration config, String[] args) {
		
		config.setFirst(false);
		List<String> servers = new ArrayList<String>();
		
		for(String arg:args) {
			if(arg.startsWith("-p=")) {
				config.setPort(arg.substring(3));
			} else if(arg.startsWith("-next=")) {
				String[] nextAddress = arg.substring(6).split(":");
				config.setNextHost(nextAddress[0]);
				config.setNextPort(nextAddress[1]);
			} else if(arg.startsWith("-log=")) {
				config.setLogfile(arg.substring(5));
			} else if(arg.equals("-first")) {
				config.setFirst(true);
			} else if(arg.startsWith("-others=")) {
				String[] others = arg.substring(8).split(",");
				for(String s:others) {
					servers.add(s);
				}
				config.setOthersServers(servers);
			} else {
				System.err.println("Argumento invalido: "+arg);
			}
		}
	}
	
	@Override
	public void update(Observable arg0, Object arg1) {
		Integer destino = ((LoggingServer) arg0).getConfig().getPort();
		System.out.println("O token chegou em localhost:" + destino);
	}
	
	public ServerManager getServerManager() {
		return serverManager;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		TokenRingServer server = new TokenRingServer(args);		
		server.getServerManager().startServer();		
	}

}
